import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:wu_you/data/cache/language_cache.dart';
import 'package:wu_you/data/cache/login_cache.dart';
import 'package:wu_you/data/repository/home_repository.dart';
import 'package:wu_you/http/http.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/main.dart';
import 'package:wu_you/model/home/home_model.dart';
import 'package:wu_you/model/home/mall_model.dart';
import 'package:wu_you/page/message/page_notice.dart';
import 'package:wu_you/page/splash/page_login.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/home_bloc.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/mall_bloc.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/widgets/cached_image_provider.dart';
import 'package:wu_you/widgets/http_list_widget.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:marquee/marquee.dart';

import 'dialog/home_notice_dialog.dart';
import 'mall/page_product_detail.dart';


///商城
class MallPage extends StatefulWidget{
  @override
  MallPageState createState() => MallPageState();
}
class MallPageState extends State<MallPage> with AutomaticKeepAliveClientMixin{

  String index = '1';
  @override
  void initState() {
    super.initState();
    _initNotice();
  }

  ///初始化公告
  void _initNotice() async {
    HomeRepository().getNewsNotice().then((value) {
      if (value == null) {
        return;
      }
      if(value.is_pop){
        showDialog(
          context: context,
          builder: (context) => HomeNoticeDialog(value: value,),
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        titleSpacing: 4,
        leading: null,
        automaticallyImplyLeading: false,
        primary: true,
        title: PreferredSize(
          preferredSize: Size.fromHeight(40.0),
          child: Container(
              height: 40,
              padding: EdgeInsets.all(8),
              margin: EdgeInsets.all(8),
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.search,
                    color: Colors.grey,
                  ),
                  Expanded(
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          "${message['search']}",
                          style: TextStyle(
                              color: HexColor("#BABABA"),fontSize: 14),
                          textAlign: TextAlign.left,),
                      )
                  )
                ],
              ).addGesture(() {
              })
          ),
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [AppColors.primaryColor, AppColors.primaryColor],
            ),
          ),
        ),
      ),
      body: _HomeCenterView()
    );
  }

  ///切换版本
  void _toggleLanguage(BuildContext context) {
    var currentLocale = Localizations.localeOf(context);
    var newLocale = currentLocale.languageCode == 'en'
        ? const Locale('zh', '')
        : const Locale('en', '');

    MyApp.setLocale(context, newLocale);
  }

  @override
  bool get wantKeepAlive => true;
}

class _HomeCenterView extends StatefulWidget{
  @override
  _HomeCenterViewState createState() => _HomeCenterViewState();
}
class _HomeCenterViewState extends State<_HomeCenterView>{

  var message;
  var future;
  var future1;
  @override
  void initState() {
    super.initState();
    future = HomeRepository.getSimplePlatformNotice(page: 1,limit: 10);
    future1 = HomeRepository().getHomePrice();
  }

  double width;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    width = MediaQuery.of(context).size.width;
    return NestedScrollView(
        headerSliverBuilder: (context, h) {
          return[
            SliverToBoxAdapter(
              child: Stack(
                children: [
                  AspectRatio(
                    aspectRatio: 3.6,
                    child: Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                          colors: [AppColors.primaryColor, AppColors.primaryColor],
                        ),
                      ),
                    ),
                  ),
                  Container(
                      height: 135,
                      padding: EdgeInsets.only(left: 10,right: 10),
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: HttpWidget<List<BannerModel>, HomeInfoBloc>(
                              create: (context) => HomeInfoBloc()..add(HttpEvent()),
                              errorBuilder: (context, error) {
                                return Container(
                                  alignment: Alignment.center,
                                  color: Colors.white,
                                  child: Text(error),
                                );
                              },
                              child: (context, data) {
                                return Swiper(
                                  onTap: (int index) {},
                                  itemBuilder: (context, index) {
                                    return Image(
                                      errorBuilder: (context, error, stackTrace){
                                        return Container(color: AppColors.primaryColor,);
                                      },
                                      image: CachedImageProvider(
                                        "${data[index].img}",
                                      ),
                                      fit: BoxFit.fill,
                                    );
                                  },
                                  itemCount: data.length,
                                  autoplay: true,
                                  pagination: SwiperPagination(
                                    margin: EdgeInsets.all(5.0),
                                    builder: DotSwiperPaginationBuilder(size: 3, activeSize: 5),
                                  ),
                                );
                              }
                          )
                      )
                  ),
                ],
              ),
            ),
            SliverToBoxAdapter(
              child: _buildNotice(),
            ),
            SliverToBoxAdapter(
              child: Divider(thickness: 4,color: HexColor("#F7F7F7"),),
            ),
            SliverToBoxAdapter(
              child: FutureBuilder(
                future: future1,
                builder: (context,priceModel){
                  if(priceModel.data != null){
                    return Container(
                      padding: EdgeInsets.only(left: 10,right: 12,bottom: 18,top: 12),
                      child: Row(
                        children: [
                          Icon(Icons.event,size: 22,color: AppColors.primaryColor,).addPadding(EdgeInsets.only(top: 5)),
                          SizedBox(width: 8,),
                          RichText(
                              text: TextSpan(children: [
                                TextSpan(
                                    text: "消费积分最新价: ",
                                    style: TextStyle(
                                        color: AppColors.textHintColor, fontSize: 14)),
                                TextSpan(
                                    text: "￥${priceModel.data}",
                                    style: TextStyle(
                                        color: AppColors.primaryColor,
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold))
                              ])),
                        ],
                      ),
                    );
                  }else{
                    return Container();
                  }
                },
              )
            ),

            ///今日特惠
            // SliverOffstage(
            //   offstage: data.length == 2 ? false : true,
            //   sliver: SliverToBoxAdapter(
            //     child: Column(
            //       mainAxisSize: MainAxisSize.min,
            //       children: [
            //         Divider(thickness: 3,color: HexColor("#F7F7F7"),),
            //         Row(
            //           mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //           children: [
            //             Row(
            //               crossAxisAlignment: CrossAxisAlignment.center,
            //               children: [
            //                 SizedBox(
            //                   width: 4,
            //                   height: 15,
            //                   child: DecoratedBox(
            //                     decoration: BoxDecoration(color: AppColors.primaryColor),
            //                   ),
            //                 ),
            //                 SizedBox(width: 6,),
            //                 Text("${message['jrth']}",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15),)
            //               ],
            //             ),
            //             Text('${message['moreText']}',style: TextStyle(fontSize: 13,color: HexColor("#FF6D7A")),).addGesture(() {
            //               NavigatorUtil.navigateToPage(context, FavorableMallPage(lId: "0",cId: data[0].category_id));
            //             })
            //           ],
            //         ).addPadding(EdgeInsets.only(left: 12,right: 12,top: 8,bottom: 4)),
            //       ],
            //     ),
            //   ),
            // ),
            // SliverOffstage(
            //     offstage: data.length == 2 ? false : true,
            //     sliver: SliverToBoxAdapter(
            //         child: HttpWidget<List<MallProductModel>, GroupProductBloc>(
            //           create: (context) => GroupProductBloc()..add(GroupProductEvent(nationality_id: "0",category_id: data[0].category_id,page: 1,size: 2,goods_type: "1")),
            //           child: (context, data) {
            //             return Container(
            //               height: 170,
            //               padding: EdgeInsets.only(left: 8,right: 8,bottom: 12),
            //               child: Row(
            //                 children: buildHorItem(data),
            //               ),
            //             );
            //           },emptyBuilder: (context){
            //           return Container(
            //               height: 120,
            //               child: Center(
            //                 child: Column(
            //                   mainAxisSize: MainAxisSize.min,
            //                   children: [
            //                     Image.asset(Utils.getImgPath("ic_empty",), width: 60,
            //                       fit: BoxFit.fitWidth,),
            //                     SizedBox(height: 10,),
            //                     Text("${message['noData']}",
            //                       style: TextStyle(color: AppColors.textHintColor, fontSize: 14),),
            //                   ],
            //                 ),
            //               )
            //           );
            //         },
            //         )
            //     )
            // ),
            ///猜你喜欢
            SliverToBoxAdapter(
              child: Column(
                children: [
                  Divider(thickness: 5,color: HexColor("#F7F7F7"),),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(
                            width: 4,
                            height: 15,
                            child: DecoratedBox(
                              decoration: BoxDecoration(color: AppColors.primaryColor),
                            ),
                          ),
                          SizedBox(width: 6,),
                          Text("${message['cnxh']}",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15),)
                        ],
                      )
                      // Text('${message['moreText']}',style: TextStyle(fontSize: 13,color: HexColor("#FF6D7A")),)
                    ],
                  ).addPadding(EdgeInsets.only(left: 12,right: 12,top: 8,bottom: 4))
                ],
              ),
            )
          ];
        },
        body: ProductListView(lId: "0",cId: "1",)
        // body: data.length == 2 ? ProductListView(lId: "0",cId: data[1].category_id,) : ProductListView(lId: "0",cId: data[0].category_id,)
    );
  }


  List<Widget> buildHorItem(List<MallProductModel> data){
    List<Widget> list = [];
    Widget child;

    data.forEach((element) {
      child = Expanded(
        child: Container(
            height: 160,
            margin: EdgeInsets.symmetric(horizontal: 3),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(6)),
                color: Colors.white
            ),
            child: Card(
              elevation: 2,
              child: Column(
                children: [
                  AspectRatio(
                      aspectRatio: 1.75,
                      child: ClipRRect(
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(6),
                          topRight: Radius.circular(6),
                        ),
                        child: Image.network(
                          "${element.img_url}",
                          fit: BoxFit.cover,
                        ),
                      )
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.all(6),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(30),
                                child: Image.network("${element.img_url}",height: 25,width: 25,fit: BoxFit.fill,),
                              ),
                              SizedBox(width: 2,),
                              Container(
                                width: width / 4,
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text("${element.name}",style: TextStyle(fontSize: 12,),maxLines: 1, overflow: TextOverflow.ellipsis,),
                                    Text("${element.title}",style: TextStyle(fontSize: 11,color: HexColor("#818181")),maxLines: 1, overflow: TextOverflow.ellipsis,)
                                  ],
                                )
                              )
                            ],
                          ),
                          Container(
                            padding: EdgeInsets.all(2),
                            decoration: BoxDecoration(
                              border: Border.all(
                                  width: 1,
                                  color: HexColor("#FE017E")
                              ),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text("${message['product0']}>",style: TextStyle(fontSize: 11,color: HexColor("#FE017E")),),
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ).addGesture(() async{
              bool isLogin = await LoginCache().get();
              if(isLogin == null || !isLogin){
                NavigatorUtil.navigateToPage(context, LoginPage());
              }else{
                NavigatorUtil.navigateToPage(context, ProductDetailInfo(productId: element.goods_id,));
              }
            })
        ),
      );
      list.add(child);
    });

    if(list.length == 1){
      list.add(
          Expanded(
            child: Container(
              height: 160,
              margin: EdgeInsets.symmetric(horizontal: 3),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(6)),
                  color: Colors.white
              ),
              child: Text(""),
            )
          )
      );
    }

    return list;
  }


  Widget _buildNotice() {
    return SizedBox(
      height: 45,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(Utils.getImgPath("ic_mall_notice"),width: 25,height: 25,),
          Expanded(
            child: Padding(
                padding: EdgeInsets.only(left: 8),
                child: FutureBuilder<List<NoticeModel>>(
                  future: future,
                  builder: (context,data){
                    List<NoticeModel> model = data.data;
                    if(model != null && model.length != 0){
                      return Marquee(
                        text: "${model[0].title} : ${Utils.removeAllHtmlTags(model[0].content)}",
                        scrollAxis: Axis.horizontal,
                        style: TextStyle(color: AppColors.primaryColor),
                        blankSpace: 50.0,
                      ).addGesture(() {
                        NavigatorUtil.navigateToPage(context, NoticeDetailPage(model[0].title, model[0].content));
                      });
                    }else{
                      return Container();
                    }
                  },
                )
            ),
          ),
        ],
      ).addPadding(EdgeInsets.all(10)),
    );
  }
}


class ProductListView extends StatefulWidget {
  final String lId;
  final String cId;
  ProductListView({
    Key key,
    this.lId,
    this.cId
  }) : super(key: key);

  @override
  _ProductListViewState createState() => _ProductListViewState();
}
class _ProductListViewState extends State<ProductListView> with AutomaticKeepAliveClientMixin{
  var message;
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    super.build(context);
    return Padding(
      padding: EdgeInsets.only(left: 10,right: 10),
      child:HttpListWidget<MallProductModel, GroupProductBloc>(
        creator: (context) => GroupProductBloc(),
        onObtainData: (context, page) {
          BlocProvider.of<GroupProductBloc>(context).add(GroupProductEvent(nationality_id: widget.lId,category_id: widget.cId,page: page,goods_type: "1"));
        },
        successBuilder: (context, data) {
          return GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 4,
              mainAxisSpacing: 4,
              childAspectRatio: 0.73,
            ),
            itemCount: data.length,
            itemBuilder: (context, index) {
              return _buildProductItem(data[index]);
            },
          );
        },
      ),
    );
  }

  Widget _buildProductItem(MallProductModel item) {
    return GestureDetector(
      onTap: () async {
        bool isLogin = await LoginCache().get();
        if(isLogin == null || !isLogin){
          NavigatorUtil.navigateToPage(context, LoginPage());
        }else{
          NavigatorUtil.navigateToPage(context, ProductDetailInfo(productId: item.goods_id,));
        }
      },
      child: Card(
        elevation: 4,
        child: PhysicalModel(
          color: Colors.transparent,
          clipBehavior: Clip.antiAlias,
          borderRadius: BorderRadius.circular(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              AspectRatio(
                aspectRatio: 1.1,
                child: Image.network(
                  "${item.img_url}",
                  fit: BoxFit.fill,
                ),
              ),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 6,right:6),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Text(
                        "${item.name}",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(fontSize: 14, color: AppColors.textColor),
                      ),
                      Text(
                        "${item.title}",
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(fontSize: 12, color: AppColors.textColor),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "无忧积分:${item.sell_price}",
                            style: TextStyle(fontSize: 12, color: AppColors.primaryColor),
                          ),
                          // Text(
                          //   "${item.sales_volume}${message['countBuy']}",
                          //   style: TextStyle(fontSize: 12, color: AppColors.textHintColor),
                          // ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => false;
}